<template>
	<view class="payment-container">
		<!-- 支付按钮 -->
		<!-- <button type="primary" @click="requestPayment">支付</button> -->
		<!-- 对话框的按钮 -->
		<!-- <button class="aibutten" type="primary" @click="aiChatting"></button> -->
		<!-- 		<view class="nav-bar">
			<view class="nav-left">
				<uni-icons type="left" size="20" color="#333333"></uni-icons>
			</view>
			<view class="nav-title">支付宝付款</view>
			<view class="nav-right"></view>
		</view> -->

		<!-- 支付金额展示 -->
		<view class="amount-section">
			<view class="amount-title">支付金额</view>
			<view class="amount-display">
				<text class="currency">¥</text>
				<text class="amount">{{requestParams.paymentAmount}}</text>
			</view>
		</view>

		<!-- 支付按钮区域 -->
		<view class="payment-actions">
			<button type="primary" class="primary-btn">打开支付宝APP付款</button>
			<button class="primary secondary-btn" @click="copyBtn">继续浏览器付款</button>
			<button class="primary download-btn">下载支付宝APP付款</button>
		</view>

	</view>


</template>

<script setup>
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		onMounted,
		ref
	} from 'vue';
	import {
		Toast
	} from "@/components/Toast.js"
	import {
		navigateTo,
		redirectTo
	} from "@/components/navigateTo.js"
	import PaymentWebView from '@/pages/alipay-proxy/index.vue'; // 引入支付页面组件
	// import {
	// 	tradeNo,
	// 	checkupdate
	// } from '@/pages/utils/api/order.js'
	const showPaymentPage = ref(false);
	import {
		useUserStore
	} from '@/stores/api.js'
	const userStore = useUserStore();
	const paymentFormHtml = ref('');
	const showWebView = ref(false);
	const alipayHtmlPath = ref('');
	let alipayPayUrl = ref("");
	const requestParams = ref({})
	// AI聊天功能
	const aiChatting = () => {
		console.log('打开AI聊天窗口');
		// 实现AI聊天窗口的逻辑
		uni.navigateTo({
			url: '/pages/ai/index'
		})
	}
	// 请求支付
	// const requestPayment =  async ( ) =>{
	// 	try {
	// 	  let  data= {
	//         amount: 0.01, // 支付金额，单位：元
	//         orderDescription: '测试订单'
	//       }
	// 	  const res = await tradeNo(data);
	// 	  let re = transformToTree(res.data);
	//       treeData.value = re[0];
	// 	  console.log('transformToTree', treeData.value)
	// 	} catch (error) {
	// 	  console.log('获取数据失败', error)
	// 	}
	// }
	// 写入临时文件（uni-app写法）
	function copyBtn() {
		uni.setClipboardData({
			//要复制的内容
			data: alipayHtmlPath.value,
			success: res => {
				uni.getClipboardData({
					success: res => {
						wx.showToast({
							title: '复制成功'
						});

						startPolling();
					}
				})
			}
		})
	}
	//支付成功之后 前端进行轮询
	const pollData = ref(null)
	const isPolling = ref(false)
	let timeoutId = null

	const startPolling = async () => {
		let data = {}
		isPolling.value = true
		try {
			const res = await uni.request({
				url: 'http://localhost:8088/alipay/checkupdate',
				method: 'post',
				data: {
					TradeNo: requestParams.value.TradeNo,
					courseids: requestParams.value.courseids,
					userId: userStore.getUserId
				}
			})
			pollData.value = res.data
			// 根据服务器返回决定下次轮询时间
			const interval = 2000;
			// 隔两秒向服务器发送请求
			timeoutId = setTimeout(startPolling, interval);
			if (pollData.value == "已完成") {
				stopPolling();
				Toast('订单支付成功');
				clearTimeout(timeoutId);
				// 跳去另一个页面  catergoryDeatil
				if (userStore.catergoryDeatil == null) {
					redirectTo("/pages/clazz/index?courseId=" + userStore.clazz.courseId);
				} else {
					redirectTo("/pages/catergoryDetail/catergoryDetail?categoryId=" + userStore.catergoryDeatil
						.categoryId + "&categoryName=" + userStore.catergoryDeatil.categoryName)
				}
				// 弹出提示
				//返回其他订单
			}
		} catch (err) {
			console.error('轮询错误:', err)
			// 出错时延迟更长
			timeoutId = setTimeout(startPolling, 10000)
		}
	}
	const stopPolling = () => {
		isPolling.value = false
		clearTimeout(timeoutId)
	}

	const requestPayment = async () => {
		try {
			// 请求后端接口，获取支付参数
			const response = await uni.request({ // 'http://172.172.9.57:8088'
				url: 'http://localhost:8088/alipay/order1',
				method: 'POST',
				data: {
					//  totalAmount 订单  TradeNo 订单号   subject 标题
					totalAmount: requestParams.value.paymentAmount, // 支付金额，单位：元
					TradeNo: requestParams.value.TradeNo,
					userId: userStore.getUserId,
					subject: "沙盒测试",
					ids: requestParams.value.ids,
					courseids: requestParams.value.courseids

				}
			});
			// 注意：uni.request返回的结构在不同平台可能不同
			const resData = response.data;
			const {
				tradeNO
			} = resData;
			if (tradeNO) {
				// const actionUrl = tradeNO.match(/action="([^"]*)"/i)?.[1] || '';
				showWebView.value = true;
				alipayHtmlPath.value = tradeNO;
				// alipayPayUrl.value = tradeNO;
				console.log(tradeNO, "tradeNO")
				// 环境判断

			} else {
				uni.showToast({
					title: '获取支付信息失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('请求支付出错:', error);
			uni.showToast({
				title: '请求支付失败，请稍后重试',
				icon: 'none'
			});
		}
	};
	// 处理支付成功
	const handlePaymentSuccess = (data) => {
		showPaymentPage.value = false;
		uni.showToast({
			title: '支付成功',
			icon: 'success'
		});
		// 这里可以进行支付成功后的操作，如跳转页面、更新订单状态等
	};

	// 处理支付失败
	const handlePaymentFailed = (message) => {
		showPaymentPage.value = false;
		uni.showToast({
			title: '支付失败: ' + message,
			icon: 'fail'
		});
	};

	// 处理支付错误
	const handlePaymentError = (error) => {
		showPaymentPage.value = false;
		uni.showToast({
			title: '支付处理出错: ' + error,
			icon: 'fail'
		});
	};
	onMounted(() => {
		requestPayment();
	})
	// totalAmount 订单  TradeNo 订单号   subject 标题
	onLoad((options) => {
		console.log(options);
		requestParams.value = options;

	})
</script>

<style scoped>
	.payment-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 999;
	}



	.ai-floating-button::after {
		border: none;
		/* removes the default border on uni-app buttons */
	}

	.ai-floating-button:active {
		background-color: #0062CC;
		/* slightly darker when pressed */
		transform: scale(0.98);
	}

	page {
		height: 100%;
	}

	.payment-container {
		min-height: 100%;
		background-color: #ffffff;
		display: flex;
		flex-direction: column;
	}

	.nav-bar {
		height: 88rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 32rpx;
		background-color: #ffffff;
		border-bottom: 1px solid #f5f5f5;
	}

	.nav-left {
		width: 44rpx;
		height: 44rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.nav-title {
		font-size: 16px;
		color: #333333;
		font-weight: 500;
		text-align: center;
		width: 100%;
	}

	.nav-right {
		width: 44rpx;
	}

	.amount-section {
		padding: 48rpx 32rpx;
		text-align: center;
	}

	.amount-title {
		font-size: 14px;
		color: #666666;
		margin-bottom: 24rpx;
	}

	.amount-display {
		display: flex;
		align-items: baseline;
		justify-content: center;
	}

	.currency {
		font-size: 24px;
		color: #333333;
		margin-right: 8rpx;
	}

	.amount {
		font-size: 48px;
		color: #333333;
		font-weight: 500;
	}

	.payment-actions {
		padding: 32rpx;
		margin-top: auto;
	}

	.primary-btn {
		background-color: #cdcdcd !important;
		border-color: #1677FF !important;
		color: #ffffff !important;
		height: 88rpx;
		line-height: 88rpx;
		font-size: 16px;
		border-radius: 44rpx;
		margin-bottom: 24rpx;
	}

	.secondary-btn {
		background-color: #ffffff !important;
		border: 1px solid #1677FF !important;
		color: #1677FF !important;
		height: 88rpx;
		line-height: 88rpx;
		font-size: 16px;
		border-radius: 44rpx;
		margin-bottom: 24rpx;
	}

	.download-btn {
		background-color: #cdcdcd !important;
		border: 1px solid #DDDDDD !important;
		color: #ffffff !important;
		height: 88rpx;
		line-height: 88rpx;
		font-size: 16px;
		border-radius: 44rpx;
		margin-bottom: 24rpx;
	}
</style>